package com.egg.service.impl;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.egg.dao.BaseDao;
import com.egg.service.RoleService;
/**
 * @项目名称：egg   
 * @类名称：RoleServiceImpl   
 * @类描述：角色实现   
 * @创建人：wangchenyang
 * @创建时间：2012-8-31 下午4:02:02   
 * @修改人：
 * @修改时间：   
 * @修改备注：   
 * @version
 */
@Service
public class RoleServiceImpl implements RoleService {

	@Autowired
	BaseDao baseDao;
	@Override
	public List<Map<String, Object>> getAllRole(Object...obj) {
		String sql="SELECT * FROM EGG_ROLE WHERE DEPT_ID=?";
		return baseDao.queryForList(sql,obj);
	}

	@Override
	public List<Map<String, Object>> getOneRole(Object...obj) {
		String sql="SELECT * FROM EGG_ROLE WHERE ID=?";
		return baseDao.queryForList(sql, obj);
	}

	@Override
	public void addRole(Object... obj) {
		String sql="INSERT INTO EGG_ROLE(ID,ROLE_NAME,ROLE_DESCRIPTION,DEPT_ID,CREATE_TIME) VALUES(SEQ_EGG_ROLE.NEXTVAL,?,?,?,?)";
		baseDao.update(sql, obj);
	}

	@Override
	public void updateRole(Object... obj) {
		String sql="UPDATE EGG_ROLE SET ROLE_NAME=?,ROLE_DESCRIPTION=? WHERE ID=?";
		baseDao.update(sql, obj);
	}

	@Override
	public void deleteRole(Object... obj) {
		String sql="DELETE FROM EGG_ROLE WHERE ID=?";
		baseDao.update(sql, obj);
	}

	@Override
	public List<Map<String, Object>> getRoleData(Object... obj) {
		String sql="SELECT ER.ROLE_NAME,ER.ROLE_DESCRIPTION,ER.ID,EUR.ID AS CHECKID FROM EGG_ROLE ER LEFT JOIN EGG_USER_ROLE EUR ON EUR.ROLE_ID=ER.ID AND EUR.USER_ID=? WHERE ER.DEPT_ID=? ORDER BY ER.ID DESC";
		return baseDao.queryForList(sql,obj);
	}

	@Override
	@Transactional
	public void assignRole(Object... obj) {
		final String userId=(String) obj[0];
		String roleId=(String) obj[1];
		//先删除之前分配的角色
		String sql1="DELETE FROM EGG_USER_ROLE WHERE USER_ID=?";
		baseDao.update(sql1, userId);
		if(roleId!=null){
			final String[] array=roleId.split(",");
			//批量添加新分配角色
			String sql2="INSERT INTO EGG_USER_ROLE(ID,USER_ID,ROLE_ID) VALUES(SEQ_EGG_UR.NEXTVAL,?,?)";
			baseDao.getJdbcTemplate().batchUpdate(sql2, new BatchPreparedStatementSetter(){
				@Override
				public int getBatchSize() {
					return array.length;
				}
				@Override
				public void setValues(PreparedStatement ps, int i)
						throws SQLException {
					ps.setInt(1, Integer.parseInt(userId));
					ps.setString(2, array[i].toString());
				}
				
			});
			//将用户状态设置为已激活
			String sql3="UPDATE EGG_USER SET USER_STATUS=1 WHERE ID=?";
			baseDao.update(sql3, userId);
		}else{
			//将用户状态设置为未激活
			String sql4="UPDATE EGG_USER SET USER_STATUS=0 WHERE ID=?";
			baseDao.update(sql4, userId);
		}
	}

}
